import java.util.Stack;

public class StackDemo {
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2= new Stack<>();
    public static void main(String[] args) {
        String s = "(()";
        int x = longestValidParentheses(s);
        System.out.println("x = " + x);
        StackDemo s1 = new StackDemo();
    }
    public  void push(int node){
        stack1.add(node);
    }
    public int pop(){
        if (stack1.isEmpty()){
            return -1;
        }
        if(stack2.size()<=0)
        while (stack1.size()!=0){
            stack2.add(stack1.pop());
        }

        return stack2.pop();
    }

    private static int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<>();
        int count = 0;
        int start = -1;
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i)=='('){
                stack.add(i);
            }else {
                if (stack.isEmpty()) {
                    start = i;
                }else{
                    stack.pop();
                    if(stack.isEmpty()){
                        count = Math.max(count,i-start);
                    }else{
                        count = Math.max(count,i-stack.peek());
                    }
                }
            }
        }
        return count;
    }
}
